from django.utils import timezone
from .models import Complaint
from accounts.models import Technician
from orders.models import Order

class ComplaintService:
    """投诉业务逻辑服务类"""
    
    @staticmethod
    def get_complaints_for_user(user):
        """根据用户角色获取投诉列表"""
        if user.role == 'customer':
            complaints = Complaint.objects.filter(customer=user)
        elif user.role == 'technician':
            try:
                technician = user.technician_profile
                complaints = Complaint.objects.filter(technician=technician)
            except Technician.DoesNotExist:
                raise PermissionError('您不是认证技师')
        else:  # admin
            complaints = Complaint.objects.all()
        
        return complaints
    
    @staticmethod
    def get_complaint_detail(complaint_id, user):
        """获取投诉详情"""
        try:
            complaint = Complaint.objects.get(id=complaint_id)
        except Complaint.DoesNotExist:
            raise ValueError('投诉不存在')
        
        # 权限检查
        if user.role == 'customer' and complaint.customer != user:
            raise PermissionError('无权查看此投诉')
        
        if user.role == 'technician':
            try:
                technician = user.technician_profile
                if complaint.technician != technician:
                    raise PermissionError('无权查看此投诉')
            except Technician.DoesNotExist:
                raise PermissionError('您不是认证技师')
        
        # 管理员可以查看所有投诉
        if user.role == 'admin':
            pass  # 管理员可以查看所有投诉
        
        return complaint
    
    @staticmethod
    def create_complaint(data, customer):
        """创建投诉"""
        if customer.role != 'customer':
            raise PermissionError('只有顾客可以提交投诉')
        
        # 验证技师是否存在且已认证
        try:
            technician = Technician.objects.get(id=data['technician'], is_verified=True)
        except Technician.DoesNotExist:
            raise ValueError("技师未认证")
        
        # 如果提供了订单，验证订单是否存在且属于当前用户
        if data.get('order'):
            try:
                order = Order.objects.get(id=data['order'], customer=customer)
                if order.technician != technician:
                    raise ValueError("订单与技师不匹配")
            except Order.DoesNotExist:
                raise ValueError("订单不存在或不属于当前用户")
        
        # 创建投诉
        complaint = Complaint.objects.create(
            customer=customer,
            technician=technician,
            order_id=data.get('order'),
            complaint_type=data['complaint_type'],
            title=data['title'],
            content=data['content'],
            evidence_images=data.get('evidence_images', [])
        )
        
        return complaint
    
    @staticmethod
    def update_complaint(complaint_id, data, admin_user):
        """更新投诉（处理投诉）"""
        try:
            complaint = Complaint.objects.get(id=complaint_id)
        except Complaint.DoesNotExist:
            raise ValueError('投诉不存在')
        
        # 只有管理员可以更新投诉状态和处理结果
        if admin_user.role != 'admin':
            raise PermissionError('只有管理员可以处理投诉')
        
        # 更新投诉信息
        if 'status' in data:
            complaint.status = data['status']
            # 如果状态更新为已解决，设置解决时间
            if data['status'] == 'resolved':
                complaint.resolved_at = timezone.now()
                # 设置处理人
                complaint.handler = admin_user
        
        if 'resolution' in data:
            complaint.resolution = data['resolution']
        
        complaint.save()
        
        return complaint
    
    @staticmethod
    def delete_complaint(complaint_id, user):
        """删除投诉"""
        try:
            complaint = Complaint.objects.get(id=complaint_id)
        except Complaint.DoesNotExist:
            raise ValueError('投诉不存在')
        
        # 只有管理员或投诉提交者可以删除投诉（且只能在待处理状态下删除）
        if user.role == 'admin' or (user == complaint.customer and complaint.status == 'pending'):
            complaint.delete()
            return True
        else:
            raise PermissionError('无权删除此投诉')